package com.kaede.hayate.modules.sys.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kaede.hayate.common.exception.SystemErrorException;
import com.kaede.hayate.modules.sys.entity.Role;
import com.kaede.hayate.modules.sys.entity.RoleAuthority;
import com.kaede.hayate.modules.sys.mapper.RoleAuthorityMapper;
import com.kaede.hayate.modules.sys.mapper.RoleMapper;
import com.kaede.hayate.modules.sys.mapper.UserRoleMapper;
import com.kaede.hayate.modules.sys.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author Kaede
 * @since 2018-06-06
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private RoleAuthorityMapper roleAuthorityMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Long createRole(Role role, Long[] authorityIds) {
        baseMapper.insert(role);
        Long roleId = role.getId();
        for(int i = 0; i < authorityIds.length; i++){
            RoleAuthority roleAuthority = new RoleAuthority();
            roleAuthority.setRoleId(roleId);
            roleAuthority.setAuthorityId(authorityIds[i]);
            roleAuthorityMapper.insert(roleAuthority);
        }
        return roleId;
    }

    @Override
    public void deleteRoleById(Long id) {

        Role role = selectById(id);
        if(role.getSysFlag()){
            throw new SystemErrorException();
        }
        baseMapper.deleteById(id);
        userRoleMapper.deleteByRoleId(id);
        roleAuthorityMapper.deleteByRoleId(id);
    }

    @Override
    public void updateRoleById(Role role, Long[] authorityIds) {
        updateById(role);
        roleAuthorityMapper.deleteByRoleId(role.getId());
        for(int i = 0; i < authorityIds.length; i++){
            RoleAuthority roleAuthority = new RoleAuthority();
            roleAuthority.setRoleId(role.getId());
            roleAuthority.setAuthorityId(authorityIds[i]);
            roleAuthorityMapper.insert(roleAuthority);
        }
    }

}
